package com.zhoust.redislock.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author 15703
 * @version 1.0
 * @Title
 * @package com.zhoust.redislock.controller
 * @date 2021/4/23 16:08
 * @desc
 */
@RestController
@Slf4j
public class RedissonLockController {

    @Autowired(required = false)
    private RedissonClient redissonClient;

    @GetMapping("testRedisson")
    public String testRedisson(){

        //根据业务key获取锁
        RLock lock = redissonClient.getLock("testRedisson");
        try{
            log.info("开始获取锁");
            lock.lock(30, TimeUnit.SECONDS);
            log.info("拿到锁。。开始执行业务逻辑");
            Thread.sleep(15000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            log.info("释放锁");
            lock.unlock();
        }
        return "se";
    }

    @GetMapping("testRedisson2")
    public String testRedisson2(){

        //根据业务key获取锁
        RLock lock = redissonClient.getLock("testRedisson");
        try{
            log.info("开始获取锁");
            lock.lock(30, TimeUnit.SECONDS);
            log.info("拿到锁。。开始执行业务逻辑");
            Thread.sleep(15000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            log.info("释放锁");
            lock.unlock();
        }
        return "se";
    }



}
